﻿using System;
using System.Diagnostics;

/* SimpleTimer 类用于在任务执行时计时，显示任务的运行时间。
 */
namespace Demo
{
    /// <summary>
    /// 用于测量代码块执行时间的简单计时器类
    /// </summary>
    public class SimpleTimer : IDisposable
    {
        /// <summary>
        /// 计时器对象
        /// </summary>
        private readonly Stopwatch _stopwatch;

        /// <summary>
        /// 任务结束时打印的消息
        /// </summary>
        private readonly string _stopMessage;

        /// <summary>
        /// 构造函数，初始化计时器并打印开始消息
        /// </summary>
        /// <param name="startMessage"></param>
        /// <param name="stopMessage"></param>
        public SimpleTimer(string startMessage = "", string stopMessage = "Elapsed time: {0:F3} s")
        {
            _stopMessage = stopMessage;

            // 初始化并启动 Stopwatch
            _stopwatch = Stopwatch.StartNew();

            // 如果有开始消息，则打印
            if (!string.IsNullOrEmpty(startMessage))
                Console.WriteLine(startMessage);
        }

        /// <summary>
        /// 实现IDisposable接口，释放计时器
        /// </summary>
        public void Dispose()
        {
            // 停止计时器
            _stopwatch.Stop();

            // 计算经过的时间
            var elapsed = _stopwatch.Elapsed.TotalSeconds;

            // 打印结束消息和经过的时间
            Console.WriteLine(_stopMessage, elapsed);
        }
    }
}
